package com.taldh;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TopKFrequent {

    @Test
    public void test() {
        Assert.assertArrayEquals(new Integer[]{1,2}, topKFrequent(new int[]{1,1,1,2,2,3}, 2).toArray());
    }

    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer, Long> collect = Arrays.stream(nums).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<Map.Entry> list = new ArrayList<>(collect.entrySet());
        list.sort((a, b) -> ((Long)b.getValue()).compareTo((Long)a.getValue()));

        ArrayList<Integer> res = new ArrayList<>(k);
        int i = 0;
        for (Map.Entry entry : list) {
            if (i > k - 1) {
                break;
            }
            res.add((Integer) entry.getKey());
            i ++;
        }
        return res;
    }

}
